package com.tangyee.home_exercise_step;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.tangyee.home_exercise_step.activities.StepHistory;
import com.tangyee.home_exercise_step.activities.StepTarget;
import com.tangyee.home_exercise_step.config.Constant;
import com.tangyee.home_exercise_step.service.StepService;
import com.tangyee.R;
import com.tangyee.home_exercise_step.activities.StepHistory;
import com.tangyee.home_exercise_step.activities.StepTarget;
import com.tangyee.home_exercise_step.bean.TargetNumberData;
import com.tangyee.home_exercise_step.config.Constant;
import com.tangyee.home_exercise_step.service.StepService;
import com.tangyee.home_exercise_step.view.StepView;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/*
展示步数的主界面
 */
public class StepActivity extends AppCompatActivity implements Handler.Callback {

    //循环取当前时刻的步数中间的时间间隔
    private long TIME_INTERVAL = 500;

    private Messenger messenger;
    private Handler delayHandler;
    private Messenger mGetReplyMessenger = new Messenger(new Handler(this));

    private StepView stepView;
    private ConstraintLayout selectTarget;
    private TextView targetNumberText;

    public String CURRENTDATE;
    private int MyFootNum;

    private boolean flag = false;

    //以bind形式开启service，故有ServiceConnection接收回调
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                messenger = new Messenger(service);
                Message msg = Message.obtain(null, Constant.MSG_FROM_CLIENT);
                msg.replyTo = mGetReplyMessenger;
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_step);
        stepView = findViewById(R.id.stepView);
        selectTarget = findViewById(R.id.select_target);
        targetNumberText = findViewById(R.id.num);
        CURRENTDATE = getTodayDate();
        flag = true;
        updateTargetNumber();
        //得到当前界面的装饰视图
        if(Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            //让应用主题内容占用系统状态栏的空间,注意:下面两个参数必须一起使用 stable 牢固的
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //设置状态栏颜色为透明
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        delayHandler = new Handler( this);

        List<TargetNumberData> targetNumberDataList = LitePal.findAll(TargetNumberData.class);
        if (targetNumberDataList.isEmpty()) {
            TargetNumberData targetNumberData = new TargetNumberData();
            targetNumberData.save();
        }

        selectTarget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StepActivity.this, StepTarget.class);
                startActivity(intent);
            }
        });


        stepView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StepActivity.this, StepHistory.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        setupService();

    }

    //开启服务
    private void setupService() {

        Intent intent = new Intent(this, StepService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }

    }

    //接受从服务端回调的步数
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Constant.MSG_FROM_SERVER:
                //更新步数
                MyFootNum = msg.getData().getInt("step" + "");
                if (flag) {
                    String targetNumber = updateTargetNumber();
                    Log.d("mmp", "handleMessage : " + targetNumber);
                    stepView.reSet(MyFootNum, Integer.valueOf(targetNumber));
                    flag = false;
                }
                delayHandler.sendEmptyMessageDelayed(Constant.REQUEST_SERVER, TIME_INTERVAL);
                break;
            case Constant.REQUEST_SERVER:
                try {
                    Message msgl = Message.obtain(null, Constant.MSG_FROM_CLIENT);
                    msgl.replyTo = mGetReplyMessenger;
                    messenger.send(msgl);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        //将activity退到后台中，
        // false参数表示只有当前activity是task根，指应用启动的第一个activity时，才有效
        // true参数表示任何activity都有效，没有限制
        moveTaskToBack(false);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消服务绑定
        unbindService(conn);
    }

    //获得今日的日期
    private String getTodayDate() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(date);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String targetNumber = updateTargetNumber();
        stepView.reSet(MyFootNum, Integer.valueOf(targetNumber));

    }

    private String updateTargetNumber() {

        TargetNumberData targetNumberData;

        List<TargetNumberData> targetNumberDataList = LitePal.findAll(TargetNumberData.class);
        if (targetNumberDataList.isEmpty()) {
            targetNumberData = new TargetNumberData();
            targetNumberData.setTargetNumber("8000");
            targetNumberData.save();
            return "8000";
        } else {
            targetNumberData = targetNumberDataList.get(0);
            String targetNumber = targetNumberData.getTargetNumber();
            targetNumberText.setText(targetNumber + "步");
            return targetNumber;
        }
//        List<StepData> list = LitePal.where("today = ?", CURRENTDATE).find(StepData.class);
//        if (!list.isEmpty()) {
//            Log.d("mmp", "updateTargetNumber !list.isEmtry()");
//            StepData stepData = list.get(0);
//            String targetNumber = stepData.getTargetNumber();
//            targetNumberText.setText(targetNumber + "步");
//            Log.d("mmp", "onReCreate : " + stepData.getTargetNumber() + "步");
//            return targetNumber;
//        } else {
//            Log.d("mmp", "updateTargetNumber list.isEmtry");
//            return "8000";
//        }
    }
}
